<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row :gutter="20">
        <a-col :span="1.2">
          <a-button @click="openAdd('xz')" type="primary">
            <template #icon>
              <icon-plus />
            </template>
            新增
          </a-button>
        </a-col>

        <a-col :span="1.5">
          <a-button type="primary" @click="openAdd('pl')"> 批量新增 </a-button>
        </a-col>
        <a-col :span="1.5">
          <a-button type="primary" @click="openUpload"> 模版导入 </a-button>
        </a-col>
        <a-col :span="1.5">
          <a-button type="primary" @click="pldel" status="danger">
            批量删除
          </a-button>
        </a-col>
      </a-row>

      <a-divider style="margin-top: 20px" />
      <a-table
        row-key="id"
        v-model:selectedKeys="deviceIdd"
        :loading="loading"
        :columns="columns"
        :data="renderData"
        :pagination="false"
        :bordered="false"
        :row-selection="rowSelections"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openAdd(record.id)" type="primary">
              添加下级
            </a-button>
            <a-button @click="openEdit(record)" type="outline"> 编辑 </a-button>
            <a-button status="danger" @click="openDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
    >
      <template #title> 组织名称 </template>
      <a-form
        ref="addModel"
        :rules="rules"
        :model="addForm"
        v-show="plbs != 'pl'"
      >
        <a-form-item field="name" label="组织名称">
          <a-input
            v-model="addForm.name"
            size="large"
            placeholder="请输入组织名称"
          />
        </a-form-item>
      </a-form>

      <a-form :model="forms" ref="addModels" v-show="plbs == 'pl'">
        <!--  :field="`posts[${index}].value`" -->
        <a-form-item
          v-for="(post, index) of forms.organization"
          :label="`组织名称`"
          :key="index"
          :field="`organization[${index}].name`"
          :rules="[{ required: true, message: '组织名称不能为空' }]"
        >
          <a-input
            class="gzmslitem"
            size="large"
            placeholder="请输入组织名称"
            v-model="forms.organization[index].name"
          />

          <a-button
            class="sc"
            @click="handleDeletes(index)"
            :style="{ marginLeft: '10px' }"
            >删除</a-button
          >
        </a-form-item>
      </a-form>
      <div class="addboxs" v-show="plbs == 'pl'">
        <a-button @click="handleAdds">新增</a-button>
      </div>
    </a-modal>

    <a-modal
      class="df"
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 导入组织 </template>
      <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item field="file" label="文件">
            <a-upload
              class="upload_box"
              @change="onChange"
              accept=".xls,.xlsx"
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
            >
              <template #upload-button>
                <a-space>
                  <a-button type="primary">选择附件</a-button>
                  <a-button @click.stop="downloadTemplate">下载模板</a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import {
    organizationTree,
    organizationSave,
    organizationUpdate,
    organizationRemove,
    downloadTemplate,
    importClass,
  } from '@/api/organization.ts';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';

  const rowSelections = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const plbs = ref('1');
  const forms = ref({
    organization: [{ name: '' }],
  });
  const handleAdds = () => {
    forms.value.organization.push({ name: '' });
  };
  const handleDeletes = (index) => {
    forms.value.organization.splice(index, 1);
  };
  const { loading, setLoading } = useLoading(true);
  const deviceIdd = ref([]);
  const pldel = () => {
    if (deviceIdd.value.length == 0) {
      Modal.confirm({
        title: '提示',
        content: '请先选中要删除的组织？',
      });
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定批量删除吗？',
        onOk() {
          Promise.all(
            deviceIdd.value.map((timetableId) => {
              return organizationRemove({
                id: timetableId,
              }).then((res) => {
                if (res.code == '200') {
                  return true; // 标记删除成功
                } else {
                  throw new Error('启用失败');
                }
              });
            })
          )
            .then((results) => {
              // 检查所有结果是否都为 true，表示删除成功
              if (results.every((result) => result === true)) {
                // 如果所有删除成功，显示成功提示
                Message.success({
                  content: '删除成功',
                });

                // 然后重新获取数据
                fetchData();
              }
            })
            .catch((err) => {
              fetchData();
              console.error('失败:', err);
            });
        },
      });
    }
  };
  const generateDataModel = () => {
    return {
      id: '',
      name: '',
      parentId: '',
    };
  };
  const rules = {
    name: [
      {
        required: true,
        message: '请输入班级名称',
      },

      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
  };
  const ruless = ref({
    organization: [
      {
        // 为第一个输入框设置默认验证规则
        name: [
          {
            required: true,
            message: '请输入班级名称',
          },

          {
            maxLength: 20,
            message: '最长20位',
          },
        ],
      },
    ] as any[],
  });
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addModel = ref();
  const addModels = ref();
  const openAdd = (parentId) => {
    plbs.value = parentId;
    const id = ref(0);
    if (parentId == 'pl' || parentId == 'xz') {
      id.value = 0;
    } else {
      id.value = parentId;
    }
    addShow.value = true;
    addForm.value = {
      ...generateDataModel(),
      parentId: id.value,
    };
    forms.value.organization = [{ name: '' }];
  };

  const handleCheck = (done) => {
    // addModel
    if (plbs.value != 'pl') {
      if (loading.value) {
        done(false);
        return;
      }
      setLoading(true);
      setTimeout(() => {
        setLoading(false);
      }, 1500);

      addModel.value.validate(
        async (errors: undefined | Record<string, ValidatedError>) => {
          if (!errors) {
            if (addForm.value.id) {
              organizationUpdate(addForm.value).then((res) => {
                if (res.code == '200') {
                  Message.success({
                    //   content: res.message,
                    content: '编辑成功',
                  });
                  done(true);
                  fetchData();
                } else {
                  done(false);
                }
              });
            } else {
              console.log('走非批量表单', addForm.value);
              organizationSave(addForm.value).then((res) => {
                if (res.code == '200') {
                  Message.success({
                    //   content: res.message,
                    content: '新增成功',
                  });
                  done(true);
                  fetchData();
                } else {
                  done(false);
                }
              });
            }
          } else {
            done(false);
          }
        }
      );
    } else {
      addModels.value.validate(
        async (errors: undefined | Record<string, ValidatedError>) => {
          if (!errors) {
            Promise.all(
              forms.value.organization.map((item) => {
                return organizationSave({
                  parentId: 0,
                  name: item.name,
                }).then((res) => {
                  if (res.code == '200') {
                    return true; // 标记删除成功
                  } else {
                    fetchData();
                    throw new Error('启用失败');
                  }
                });
              })
            )
              .then((results) => {
                console.log('批量新增', results);
                // 检查所有结果是否都为 true，表示删除成功
                if (results.every((result) => result === true)) {
                  // 如果所有删除成功，显示成功提示
                  Message.success({
                    content: '新增成功',
                  });
                  addShow.value = false;
                  // 然后重新获取数据
                  forms.value.organization = [{ name: '' }];
                  fetchData();
                }
              })
              .catch((err) => {
                fetchData();
                forms.value.organization = [{ name: '' }];
                console.error('失败:', err);
              });
          }
        }
      );
      console.log('走批量表单');
      //
    }
  };

  const openEdit = (item) => {
    addForm.value = Object.assign({}, item);
    addShow.value = true;
  };

  const handleCancel = () => {
    addShow.value = false;
  };
  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        organizationRemove({
          id: item.id,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };

  const columns = computed<TableColumnData[]>(() => [
    {
      title: '组织名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const renderData = ref([]);

  const fetchData = async () => {
    setLoading(true);
    try {
      organizationTree().then((res) => {
        renderData.value = res.data;
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const uploadRules = {
    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
  };
  const onChange = (fileList) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };
  const generateUploadModel = () => {
    return {
      file: null,
      // deptId: '',
    };
  };
  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  const openUpload = () => {
    uploadForm.value = generateDataModel();
    uploadShow.value = true;
  };
  const uploadCancel = () => {
    uploadShow.value = false;
  };

  const uploadCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          formData.append('file', uploadForm.value.file);
          importClass(formData).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '新增成功',
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const reset = () => {
    uploadShow.value = false;
    uploadForm.value = generateDataModel();
    fetchData();
  };
  fetchData();
</script>
